<template>
  <div>
    <el-row :gutter="20" v-if="type">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:project:invoice:add']" @click="openDialog(null)">增加</el-button>
<!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['md:project:invoice:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="8">
        <div class="grid-content bg-purple text">
          <span>需开票总金额(元)：{{ bidAmount }}</span>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content bg-purple text">
          <span>已开票总金额(元)：{{ allAmount }}</span>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content bg-purple text">
          <span>未开票总金额(元)：{{ $decimal(bidAmount).minus(allAmount).toNumber() <= 0 ? 0 : $decimal(bidAmount).minus(allAmount).toNumber()}}</span>
        </div>
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      v-loading="loading"
      highlight-current-row
      max-height="300"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="invoiceDate"
        label="开票日期"
        align="center"
      />
      <el-table-column
        property="invoiceAmount"
        label="金额(元)"
        align="center"
      />
      <el-table-column
        property="invoiceRatio"
        label="比例(%)"
        align="center"
      />
      <el-table-column
        property="remark"
        label="备注"
        align="center"
        v-if="type"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
        width="100"
        v-if="type"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        width="160"
        sortable
        v-if="type"
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="type && ($auth.hasPermi('md:project:invoice:edit') || $auth.hasPermi('md:project:invoice:remove'))"
      >
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['md:project:invoice:edit']" @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" type="text" v-hasPermi="['md:project:invoice:remove']" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :autoScroll="false"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal
      :fullscreen="device =='mobile'"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-form-item label="开票日期" prop="invoiceDate">
          <el-date-picker
            v-model="form.invoiceDate"
            type="date"
            :picker-options="pickerOptions"
            placeholder="选择开票日期"
            value-format="yyyy-MM-dd"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="金额" prop="invoiceAmount">
          <el-input
            v-model.trim="form.invoiceAmount"
            :min="0"
            type="number" placeholder="请输入金额"
            @input="inputHandler"
            @blur="blurHandler"
            style="width: 100%"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="比例" prop="invoiceRatio">
          <el-input v-model="form.invoiceRatio" disabled style="width: 100%">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/md/project/invoice";
// import ProvinceData from '@/views/crm/data/province.json'
import {getUserProfile} from "@/api/system/user";
import { mapGetters } from 'vuex'

export default {
  name: 'ProjectInvoice',
  // dicts: ['sys_key_customer_basis'],
  props: {
    projectInfo: {
      type: Object,
      required: true,
    },
    type: {
      type: Number,
      default: 1, // 1是全部功能 0是仅查看
    },
    change: {
      type: Function,
      default: () => {}
    },
  },
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 项目日期
      projectDate: [],
      currentAmount: 0, // 当前预算金额
      allAmount: 0, // 总预算金额
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        invoiceAmount: null, // 开票金额
        invoiceDate: '', // 开票日期 到日
        invoiceRatio: '', // 开票比例
        projectId: null, // 项目ID
        createBy: "", // 用户
        createTime: "", // 创建时间
        id: null, // id
        projectName: "", // 项目名称
        remark: "", // 备注
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        invoiceAmount: [
          { required: true, message: '请填写金额', trigger: 'blur' }
        ],
        invoiceDate: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        projectId: null, // 项目id
        name: "", // 设备名称
        pageNum: 1,
        pageSize: 10,
        startDate: '',
        endDate: '',
      },
      // 日期选择框设置不能选今日之后的日期
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
    }
  },
  computed:{
    ...mapGetters([
      'device'
    ]),
    bidAmount() {
      const num = this.projectInfo.bidAmount ?? 0
      return this.$decimal(num).mul(10000).toNumber()
    },
  },
  watch: {
    projectDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if(newV !== 1) {
          this.form.basis = null
        }
      }
    },
    projectInfo: {
      deep: true,
      handler(newV) {
        this.queryParams.projectId = newV.id
        this.searchHandler()
      },
    },
  },
  created() {
    // this.provinceList = ProvinceData
    this.queryParams.projectId = this.projectInfo.id
    this.getList()
    this.getUserinfo()
  },
  methods: {
    // 用户输入的回调
    inputHandler(e) {
      if(+e < 0) this.form.invoiceAmount = 0
    },
    // 失去焦点的回调
    blurHandler() {
      const num = this.form.invoiceAmount / (this.projectInfo.bidAmount * 10000)
      this.form.invoiceRatio = +((Math.floor(num * 100) / 100) ?? 0) * 100
      // this.form.invoiceRatio = +(num.toFixed(2) ?? 0) * 100
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if(+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if(res.code === 200) {
        this.tableData = res.rows
        this.total = res.total

        this.allAmount = res.amount

        this.currentAmount = this.tableData.reduce((acc, cur) => acc + (cur.invoiceAmount ?? 0), 0)
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
      this.$emit('change')
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/invoice/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `invoices_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      // if(this.form.isImportant === 1 && !(this.form.basis)) {
      //   this.$notify({
      //     title: '警告',
      //     message: '请选择重点依据',
      //     type: 'warning'
      //   });
      //   return false
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
        projectId: this.projectInfo.id,
        type: 1,
      }
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
      this.$emit('change')
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
        projectId: this.projectInfo.id,
        type: 1,
      }
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
      this.$emit('change')
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.projectDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>
<style scoped lang="scss">
.grid-content.text{
  margin-top: 10px;
  color: red;
}
</style>
